using GalaSoft.MvvmLight;
using WebSiteAdminTool.UI.ViewModels.Base;
using System;
using WebSiteAdminTool.UI.Views.Base;
using WebSiteAdminTool.UI.Utils.Commands;
using WebSiteAdminTool.UI.Utils.Interfaces;
using WebSiteAdminTool.UI.Services.Navigation;
using WebSiteAdminTool.UI.Views;
using WebSiteAdminTool.UI.Services.Navigation.Messages;
using System.Collections.Generic;
using WebSiteAdminTool.UI.Services.Messaging;

namespace WebSiteAdminTool.UI.ViewModels
{
    /// <summary>
    /// Main page view model
    /// </summary>
    public class MainViewModel : BaseNavigableViewModel
    {
        #region private data

        private List<Uri> _navigationHistory = null;
        private int _selectedUriIndex = -1;

        #endregion

        #region ctors

        public MainViewModel()
            : base()
        {
            base.InitViewModel();
        }

        #endregion

        #region initialization

        protected override void RegisterListeners()
        {
            MessageManager.RegisterListener<NavigationMessage<Uri>>(
                this, message => NavigateTo(message.Content));
            MessageManager.RegisterListener<NavigateBackMessage<bool>>(
                this, message => NavigateBack(message.Content));

            base.RegisterListeners();
        }

        protected override void SetDefaultValues()
        {
            base.SetDefaultValues();

            _navigationHistory = new List<Uri>();
            NavigateTo(NavigationService.GetPageUri<HomePage>());
        }

        #endregion

        #region public props

        public Uri SelectedPage
        {
            get 
            {
                if (_selectedUriIndex >= 0 && _navigationHistory.Count > _selectedUriIndex)
                    return _navigationHistory[_selectedUriIndex];
                return null;
            }
            //set
            //{
            //    _navigationHistory.Add(value);
            //    _selectedUriIndex = _navigationHistory.Count - 1;
            //    RaisePropertyChanged("SelectedPage");
            //}
        }

        #endregion

        #region helpers

        public void NavigateTo(Uri pageUrl)
        {
            _navigationHistory.Add(pageUrl);
            _selectedUriIndex = _navigationHistory.Count - 1;
            RaisePropertyChanged("SelectedPage");
        }
        
        private void NavigateBack(bool navigate)
        {
            if (navigate && _selectedUriIndex > 0)
            {
                _selectedUriIndex--;
                RaisePropertyChanged("SelectedPage");
            }
        }

        #endregion
    }
}